package 富婆梦.第一阶段.第七周IO流;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.第七周
 * @ClassName: GetChannel
 * @Author: hemengjin
 * @Description: nio通道的使用
 * @Date:2021/9/12 16:41
 * @Version: 1.0
 */
public class GetChannel {
    private static final int BSIZE = 1024;

    public static void main(String[] args) {
        File file = new File("D:/何梦锦的宝藏/Java学习/tata.txt");
        try {
            //写一个文件
            FileOutputStream fo = new FileOutputStream(file);
            FileChannel fc = fo.getChannel();
            fc.write(ByteBuffer.wrap("Some text".getBytes()));
            fc.close();
            //在文件的末尾加入
            fc = new RandomAccessFile("data.txt", "rw").getChannel();
            fc.position(fc.size());//定位到最后一行
            fc.write(ByteBuffer.wrap("Some more".getBytes()));
            fc.close();
            //读文件
            fc = new FileInputStream("data.txt").getChannel();
            ByteBuffer buff = ByteBuffer.allocate(BSIZE);
            fc.read(buff);
            buff.flip();
            while (buff.hasRemaining()) {
                System.out.println((char) buff.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
